#!/bin/bash
#

fn="$1"

VIM=vi

if [[ "$1" == "-g" ]]; then
	VIM=gvim
	fn="$2"
fi

if [[ "$1" == "clean" ]]; then
	for ff in $(find . -type d); do
		rm -rf $ff/.*~
		rm -rf $ff/.*.swp
	done
	exit 0
fi

find . -type f -iname "*$fn*" > /tmp/.ffv.tmp

[[ ! -r /tmp/.ffv.tmp ]] && echo ">>> file cache error!" && exit 0

ffn=0

lines=$(wc -l < /tmp/.ffv.tmp)

if [[ $lines == "0" ]]; then
	echo ">>> no file found, check the name please!"
	exit 0
elif [[ $lines == "1" ]]; then
	$VIM $(cat /tmp/.ffv.tmp)
else
	while [[ "$ffn" != $lines ]]; do
		let "ffn+=1" 
		echo "$ffn : $(sed -n "${ffn}p" /tmp/.ffv.tmp)"
	done
	echo "-----------------------------------------------"
	read -p "which file (No.) you want: " yon
	[[ $yon =~ ^[0-9]+$ ]] && ffn=$yon || exit 0
	$VIM $(sed -n "${yon}p" /tmp/.ffv.tmp)
fi
